﻿using System;
using System.Web.UI.WebControls;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.property;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.propertytype;
using umbraco.cms.businesslogic.media;
using System.Text;

namespace idseefeld.com.images
{
    public partial class installImageAddOn : System.Web.UI.UserControl
    {
        private const int DataTypeDefinitionId = -88;//default Textstring

        //private const string dataTypeName = "Textstring";//"Textbox multiple";
        //private const string docAlias = "Standard";
        //private const string porpAlias = "demoProp";
        //private const string porpDefault = "This property was set via package-install.";
        //private const string porpTabLower = "content";
        //private readonly bool firstPropOnTab = true;

        private const string defaultImageTypeAlias = "Image";
        private const string defaultFolderTypeAlias = "Folder";
        private const string defaultFileTypeAlias = "File";
        private const string newImageTypeText = "Image Extra";
        private const string newImageTypeAlias = "ImageExtra";
        private const string newFolderTypeText = "Folder Extra";
        private const string newFolderTypeAlias = "FolderExtra";



        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            install.Visible = false;
            result.Text = InstallExtraImageFolderMediaType();
            finished.Visible = true;
        }
        private string InstallExtraImageFolderMediaType()
        {
            StringBuilder result = new StringBuilder("New media types <strong>" + newFolderTypeText + "</strong> and <strong>" + newImageTypeText + "</strong> successfully installed.<br/><ul>");

            try
            {
                umbraco.BusinessLogic.User admin = umbraco.BusinessLogic.User.GetUser(0);

                //ToDos create datatypes: Image Cropper Png, Folder Browser Png, Upload Png
                CreateNewDatatype("Image Cropper Png", "93FBB70B-DD9E-4BBC-B581-C8B45E3EBC1C");
                CreateNewDatatype("Folder Browser Png", "5D559F5B-F929-49B6-B1F3-0E2E97BBCBF2");
                CreateNewDatatype("Upload Png", "5B54A8D3-E70D-4136-B5D5-60612B51F8FA");

                MediaType newImageType = null;
                MediaType newFolderType = null;
                MediaType folderType = null;
                MediaType imageType = null;
                MediaType fileType = null;
                PropertyType pt;
                string imageIconUrl = "mediaImagePlus.gif";
                string folderIconUrl = "folderPlus.gif";
                string thumbnail = "folder.png";
                foreach (MediaType type in MediaType.GetAllAsList())
                {
                    if (type.Alias.Equals(defaultImageTypeAlias))
                    {
                        //iconUrl = type.IconUrl;
                        thumbnail = type.Thumbnail;
                    }
                    else if (type.Alias.Equals(defaultFolderTypeAlias))
                    {
                        folderType = type;
                    }
                    else if (type.Alias.Equals(newImageTypeAlias))
                    {
                        newImageType = type;
                    }
                    else if (type.Alias.Equals(newFolderTypeAlias))
                    {
                        newFolderType = type;
                    }
                    else if (type.Alias.Equals(defaultImageTypeAlias))
                    {
                        imageType = type;
                    }
                    else if (type.Alias.Equals(defaultFileTypeAlias))
                    {
                        fileType = type;
                    }
                }
                if (newFolderType != null)
                {
                    result.AppendFormat("<li>Media type <strong>{0}</strong> already existed.</li>", newFolderTypeText);
                }
                else
                {
                    //Folder Extra
                    newFolderType = MediaType.MakeNew(admin, newFolderTypeAlias);
                    newFolderType.Alias = newFolderTypeAlias;
                    newFolderType.Text = newFolderTypeText;
                    newFolderType.IconUrl = folderIconUrl;
                    newFolderType.Thumbnail = thumbnail;
                    //tabs
                    int ContentsTabId = newFolderType.AddVirtualTab("Contents");
                    //properties
                    pt = newFolderType.AddPropertyType(GetDataTypeDefinitionByName("Folder Browser Png"), "contents", "Contents:");
                    newFolderType.SetTabOnPropertyType(pt, ContentsTabId);

                    //add newFolderType to folder type structur
                    int[] folderChildIds = new int[folderType.AllowedChildContentTypeIDs.Length + 1];
                    folderChildIds[0] = newFolderType.Id;
                    for (int i = 1; i < folderChildIds.Length; i++)
                    {
                        folderChildIds[i] = folderType.AllowedChildContentTypeIDs[i - 1];
                    }
                    folderType.AllowedChildContentTypeIDs = folderChildIds;

                    newFolderType.AllowedChildContentTypeIDs = folderType.AllowedChildContentTypeIDs;
                }
                if (newImageType != null)
                {
                    result.AppendFormat("<li>Media type <strong>{0}</strong> already existed.</li>",newImageTypeText);
                }
                else
                {
                    //Image Extra
                    newImageType = MediaType.MakeNew(admin, newImageTypeAlias);
                    newImageType.Alias = newImageTypeAlias;
                    newImageType.Text = newImageTypeText;
                    newImageType.IconUrl = imageIconUrl;
                    newImageType.Thumbnail = thumbnail;
                    //tabs
                    int ImageTabId = newImageType.AddVirtualTab("Image");
                    int CropsTabId = newImageType.AddVirtualTab("Crops");
                    //properties
                    pt = newImageType.AddPropertyType(GetDataTypeDefinitionByName("Upload Png"), "umbracoFile", "Upload image");
                    newImageType.SetTabOnPropertyType(pt, ImageTabId);
                    pt = newImageType.AddPropertyType(GetDataTypeDefinitionByName("Label"), "umbracoWidth", "Width");
                    newImageType.SetTabOnPropertyType(pt, ImageTabId);
                    pt = newImageType.AddPropertyType(GetDataTypeDefinitionByName("Label"), "umbracoHeight", "Height");
                    newImageType.SetTabOnPropertyType(pt, ImageTabId);
                    pt = newImageType.AddPropertyType(GetDataTypeDefinitionByName("Label"), "umbracoBytes", "Size");
                    newImageType.SetTabOnPropertyType(pt, ImageTabId);
                    pt = newImageType.AddPropertyType(GetDataTypeDefinitionByName("Label"), "umbracoExtension", "Type");
                    newImageType.SetTabOnPropertyType(pt, ImageTabId);

                    pt = newImageType.AddPropertyType(GetDataTypeDefinitionByName("Image Cropper Png"), "imageCrops", "Image Crops");
                    newImageType.SetTabOnPropertyType(pt, CropsTabId);

                    pt = newImageType.AddPropertyType(GetDataTypeDefinitionByName("Label"), "originalUploadFile", "originalUploadFile");

                    //add newMediaType to folder type structur
                    int[] folderChildIds = new int[folderType.AllowedChildContentTypeIDs.Length + 1];
                    folderChildIds[0] = newImageType.Id;
                    for (int i = 1; i < folderChildIds.Length; i++)
                    {
                        folderChildIds[i] = folderType.AllowedChildContentTypeIDs[i - 1];
                    }
                    folderType.AllowedChildContentTypeIDs = folderChildIds;

                    folderChildIds = new int[newFolderType.AllowedChildContentTypeIDs.Length + 1];
                    folderChildIds[0] = newImageType.Id;
                    for (int i = 1; i < folderChildIds.Length; i++)
                    {
                        folderChildIds[i] = newFolderType.AllowedChildContentTypeIDs[i - 1];
                    }
                    newFolderType.AllowedChildContentTypeIDs = folderChildIds;
                }
            }
            catch (Exception ex)
            {
                result.Clear();
                result.AppendFormat( "Installion not succesful: {0}", ex.Message);
            }
            return result.ToString();
        }

        #region helper

        private void CreateNewDatatype(string name, string id){
            
        }

        private DataTypeDefinition GetDataTypeDefinitionByName(string name)
        {
            DataTypeDefinition dt = null;
            DataTypeDefinition[] allDts = DataTypeDefinition.GetAll();
            foreach (DataTypeDefinition d in allDts)
            {
                if (d.Text == name)
                {
                    dt = d;
                    break;
                }
            }

            if (dt == null)
                dt = new DataTypeDefinition(DataTypeDefinitionId);
            return dt;
        }
        private int GetTabIdByName(ContentType ct, string porpTabLower)
        {
            int id = -1;
            ContentType.TabI[] tabs = ct.getVirtualTabs;
            foreach (ContentType.TabI t in tabs)
            {
                if (t.Caption.ToLower() == porpTabLower)
                {
                    id = t.Id;
                    break;
                }
            }
            return id;
        }

        //private void DefineNewProperty()
        //{
        //    DataTypeDefinition dt = GetDataTypeDefinitionByName(dataTypeName);
        //    ContentType ct = umbraco.cms.businesslogic.ContentType.GetByAlias(docAlias);
        //    PropertyType pt = ct.getPropertyType(porpAlias);
        //    if (pt == null)
        //    {
        //        ct.AddPropertyType(dt, porpAlias, porpAlias);
        //        pt = ct.getPropertyType(porpAlias);
        //        pt.SortOrder = firstPropOnTab ? 0 : ct.PropertyTypes.Count;
        //        int tabId = GetTabIdByName(ct, porpTabLower);
        //        if (tabId > 0)
        //        {
        //            ct.SetTabOnPropertyType(pt, tabId);
        //            if (pt.SortOrder == 0)
        //                foreach (PropertyType type in ct.PropertyTypes)
        //                {
        //                    if (type.TabId == tabId && type.Id != pt.Id)
        //                    {
        //                        type.SortOrder++;
        //                    }
        //                }
        //        }
        //    }
        //}
        //private void UpdateDocs(umbraco.cms.businesslogic.Content content)
        //{
        //    Document doc = new Document(content.Id);

        //    if (doc.ContentType.Alias == docAlias)
        //        UpdateNewProperty(doc);
        //    foreach (Document child in doc.Children)
        //    {
        //        UpdateDocs(child);
        //    }
        //}

        //private void UpdateNewProperty(Document doc)
        //{
        //    Property prop = doc.getProperty(porpAlias);
        //    if (prop != null)
        //    {
        //        if (String.IsNullOrEmpty(prop.Value.ToString()))
        //        {
        //            prop.Value = porpDefault;
        //            counter++;
        //        }
        //    }
        //}
        #endregion
    }
}